//
//  FriendList.swift
//  foodApp1
//
//  Created by JennyShi on 2018/3/7.
//  Copyright © 2018年 Apple Inc. All rights reserved.
//

import Foundation

import UIKit
import os.log

class Friend: NSObject, NSCoding {
    
    struct PropertyKey {
        static let userName = "userName"
        static let goingOrNot = "goingOrNot"
    }
    
    
    //MARK: Properties
    
    var userName: String
    var goingOrNot: String
    
    static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
    static let ArchiveURL = DocumentsDirectory.appendingPathComponent("Friends")
    
    
    //MARK: Initialization
    
    func encode(with aCoder: NSCoder) {
        aCoder.encode(userName, forKey: PropertyKey.userName)
        aCoder.encode(goingOrNot, forKey: PropertyKey.goingOrNot)
    }
    
    required convenience init?(coder aDecoder: NSCoder) {
        // The title is required. If we cannot decode a name string, the initializer should fail.
        guard let userName = aDecoder.decodeObject(forKey: PropertyKey.userName) as? String else {
            os_log("Unable to decode the username for a Friend object.", log: OSLog.default, type: .debug)
            return nil
            
        }
        
        // Because photo is an optional property of Meal, just use conditional cast.
        let goingOrNot = aDecoder.decodeObject(forKey: PropertyKey.goingOrNot) as? String
        // Must call designated initializer.
        self.init(userName: userName, goingOrNot: goingOrNot!)
        
    }
    
    init?(userName: String, goingOrNot: String) {
        
        // Initialization should fail if there is no name or if the rating is negative.
        if userName.isEmpty || goingOrNot.isEmpty  {
            return nil
        }
        
        // Initialize stored properties.
        self.userName = userName
        self.goingOrNot = goingOrNot
    }
    
}
